package com.htdc.web.controller;

import com.htdc.web.bean.*;
import com.htdc.web.dao.BillDao;
import com.htdc.web.service.AgreementService;
import com.htdc.web.service.BillService;
import com.htdc.web.service.ProjectService;
import com.htdc.web.service.RoomService;
import com.htdc.web.utils.DateUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/Agreement")
public class AgreementController {
    @Autowired
    private AgreementService agreementService;
    @Autowired
    private BillService billService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private ProjectService projectService;

    //List主页
    @RequestMapping("/AgreementHome")
    private String AgreementHome(HttpServletRequest request,HttpSession session,@Param("CPAMap")Map CPAMap,@Param("pid")Integer pid
    ){ System.out.println("正在进入合同管理主页");
       System.err.println(request.getRequestURI());
        //通过
        if(CPAMap!=null){
            session.setAttribute("agreements",agreementService.showAllAgreementByPid(pid));
            session.setAttribute("CPAMap",CPAMap);
            session.setAttribute("pid",pid);//每一个项目的Pid都放进去
        }
        return "/agreement/agreementList";
    }

    //终止合同
    @RequestMapping("/stopAgreement")
    private  String stopAgreement(HttpServletRequest request,HttpSession session,@Param("aid")String aid,@Param("stopAgreement")String stopAgreement ){
        System.err.println("打印要中止合同的ID"+stopAgreement);
        agreementService.stopAgreement(aid);
        return "/agreement/agreementList";
    }

    //显示所有异常（欠费）合同
    @RequestMapping("/showAbnormal")
    private  String historyByRid(HttpServletRequest request){
        System.out.println("显示所有异常合同ing");
        List<Agreement> abnormalAgreements=agreementService.showAllAbnormalAgreements();
        for(Agreement agreement:abnormalAgreements){
            System.err.println(agreement);
        }
        request.setAttribute("abnormalAgreements",abnormalAgreements);
        return "/agreement/abnormal";
    }

    //跳转到添加合同的页面弹窗
    @RequestMapping("/toAddAgm")
    private String toAddAgm(HttpServletRequest request, HttpSession session){
        Integer pid=(Integer)session.getAttribute("pid");
        session.setAttribute("pid",pid);
        List<Room> rooms=roomService.getRoomsByPid(pid);
        session.setAttribute("rooms",rooms);
        return "agreement_add";
    }

    //添加合同
    @RequestMapping(value = "/addAgreement")
    @ResponseBody
    private Object addAgreement(@Param("aid") String aid,@Param("cycle")String cycle,
                                @Param("rentTime") Date rentTime, @Param("rentEnd") Date rentEnd,
                                @Param("rentCash") double rentCash, @Param("freeTime") long freeTime,
                                @Param("price") double price,@Param("rentPattern")  String rentPattern,
                                @Param("growthRate")double growthRate,@Param("pname")String
                                    pname,@Param("ptel")long ptel,@Param("rids") String [] rids){
        System.out.println("正在添加合同");
        for (String a:rids){//每一个房间都有一个单独的合同
            Agreement agreement=new Agreement();
            int rid=Integer.parseInt(a);
            agreement.setAid(aid);
            Room room=roomService.getRoomByRid(rid);
            agreement.setRid(room.getRid());
            agreement.setPid(room.getPid());
            agreement.setRentCash(rentCash);
            agreement.setRentState("出租中");
            agreement.setRentPattern(rentPattern);
           //通过房间RID获取房间面积：
            agreement.setArea(room.getRoomArea());
            agreement.setCycle(cycle);
            //通过传入单价和面积计算每个周期基本价格
            double billPrice=price*agreement.getArea();
            agreement.setFreeTime(freeTime);
            agreement.setRentTime(rentTime);
            agreement.setRentEnd(rentEnd);
            String start=rentTime.toString();
            String end=rentEnd.toString();
            //把账单需要的基础数据传给生成账单，返回合同的预计总收益。即planRentMoney。
            //生成账单需要的数据有：每周期单价，增长率，周期，免租期，开始时间，结束时间，合同ID
            agreement.setPlanRentMoney(billService.calculateBill(aid,billPrice,growthRate,cycle,freeTime,start,end));
            agreement.setGrowthRate(growthRate);
            agreement.setRentCash(rentCash);
            System.err.println(agreement);
            agreementService.addAgreements(agreement);
        }
        return "success";
    }

    //根据房间号查房间历史合同
    private String showHistoryByRid(@Param("rid") Integer rid,HttpServletRequest request){
        List<Agreement>agreements=agreementService.show(rid);
        request.setAttribute("agreements",agreements);
        return "/agreement/history";
    }

    @RequestMapping("/home")
    private String agreementHome(HttpServletRequest request){
        List<Company> companies =projectService.getAllCompanies();
        Map<Company,Map<ProjectTb,List<Agreement>>> CPAMap=new HashMap<>();
        for (Company company : companies) {
            List<ProjectTb> projects = projectService.getProjectByCid((int)company.getCid());
            Map<ProjectTb,List<Agreement>> PAMap = new HashMap<>();
            for (ProjectTb project : projects) {
                List<Agreement>agreementList= agreementService.showAllAgreementByPid((int) project.getPid());
                System.err.println("打印项目ID"+project.getPid());
                for (Agreement agreement:agreementList){
                    System.err.println(agreement);
                }
                PAMap.put(project,agreementList);
            }
            CPAMap.put(company,PAMap);
        }
        request.setAttribute("CPAMap",CPAMap);

        return "agreement/agreementIndex";
    }

}
